package com.nextive.weightlogger.util;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;

/**
 * Utilities to retrieve android content such as contacts.
 * 
 * @author Federico Baseggio <fedebaseggio@gmail.com>
 */
public class ContentUtil {
	private ContentResolver contentResolver;
	
	/**
	 * Constructor.
	 * 
	 * @param contentResolver
	 *            A content resolver to perform queries.
	 */
	public ContentUtil(ContentResolver contentResolver)
	{
		this.contentResolver = contentResolver;
	}

	/**
	 * Retrieves the id of the contact specified by the given contactUri.
	 * 
	 * @param contactUri
	 *            The uri of the contact.
	 * @return The contact id.
	 */
	public String getContactId(Uri contactUri) {
		Cursor cursor = contentResolver.query(contactUri,
				new String[] { ContactsContract.Contacts._ID }, null, null,
				null);

		if (cursor != null && cursor.moveToFirst()) {
			return cursor.getString(cursor
					.getColumnIndex(ContactsContract.Contacts._ID));
		}
		cursor.close();
		return null;
	}

	/**
	 * Retrieves the first e-mail address (if any) of the contact specified by
	 * the given contactUri.
	 * 
	 * @param contactUri
	 *            The uri of the contact.
	 * @return The first e-mail address of the contact (if any), or null if
	 *         the contact has no e-mail address.
	 */
	public String getEmail(Uri contactUri) {
		String contactId = getContactId(contactUri);
		if (contactId != null)
		{
			return getEmail(contactId);
		}
		return null;
	}

	/**
	 * Retrieves the first e-mail address (if any) of the contact specified by
	 * the given contact id.
	 * 
	 * @param contactId
	 *            The id of the contact.
	 * @return The first e-mail address of the contact (if any), or null if
	 *         the contact has no e-mail address.
	 */
	public String getEmail(String contactId) {
		Cursor cursor = contentResolver
				.query(
						ContactsContract.CommonDataKinds.Email.CONTENT_URI,
						new String[] { ContactsContract.CommonDataKinds.Email.DATA },
						ContactsContract.CommonDataKinds.Email.CONTACT_ID
								+ " = ?", new String[] { contactId }, null);

		if (cursor != null && cursor.moveToFirst()) {

			return cursor
					.getString(cursor
							.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
		}
		cursor.close();

		return null;
	}
}
